<?php

namespace App\Services\Goods\Traits;

use App\Services\Manage\Api;
trait BaseCheckCate
{
	/**
	 * @author:      李颖
	 * @DateTime:    2017-07-25 18:46:56
	 * @Description: 添加分类或者修改分类时，做一些基本的分类的验证
	 * 前提：表结构: id pid status app_id other_app_read 字段必须有 action（标识符）可有可没有
	 */
	private function _baseCheckCate(array $data, string $addScene = '', string $editScene = '', string $logicPath, string $getDbCateInfoMethod = 'dbCateInfo', string $checkActionMethod = 'checkAction'): array
	{
		$logic = new $logicPath;
		$manageAppId = Api::getAppId();  //总后台app_id
		$returnRes = [];
        
        //修改分类时
        if(isset($data['id']) && $data['id']){
        	$cateInfo = $logic->$getDbCateInfoMethod($data);
        	if(!$cateInfo){ return verify_err(null, '该分类不存在'); }
        	if($data['app_id'] != $manageAppId && $data['app_id'] != $cateInfo['app_id']){ return verify_err(null, '该app_id无权操作该分类'); }
        	if($cateInfo['pid']){  
	        	if(isset($data['other_app_read']) && $data['other_app_read'] != $cateInfo['other_app_read']){ return verify_err(null, '不可修改子类的other_app_read'); }
	        }
	        if(isset($data['action']) && $data['action'] != $cateInfo['action']){
	            $checkAction = $logic->$checkActionMethod($data);
	            if($checkAction['status'] != SUCCESS_STATUS){ return verify_err(null, '该识别码action已存在'); }
	        }
	        if($manageAppId != $data['app_id'] && isset($data['is_public']) && $data['is_public'] == 1){ return verify_err(null, '公共分类的所属应用必须为亚数后台'); }
	        $returnRes = $cateInfo;
        }
        //添加分类时
        if(!isset($data['id'])){
	        if($manageAppId != $data['app_id'] && $data['is_public'] == 1){ return verify_err(null, '只有亚数后台才可以添加公共应用的分类'); }
	        if($data['pid']){
	    		$parentInfo = $logic->$getDbCateInfoMethod(['id'=>$data['pid']]);
	    		if(!$parentInfo || $parentInfo['status'] != 1){	return verify_err(null, '该父类不存在或该父类的状态不正常'); }
	    		if($parentInfo['app_id'] != $data['app_id'] || $parentInfo['other_app_read'] != (string)$data['other_app_read']){ return verify_err(null, '子类的app_id和other_app_read需和父类保持一致'); }
	    		$returnRes = $parentInfo;
	    	}
	    	if(isset($data['action'])){
    			$checkAction = $logic->$checkActionMethod($data);
		        if($checkAction['status'] != SUCCESS_STATUS){ return verify_err(null, '该识别码action已存在'); }
    		}
        }
        return auto_success($returnRes, '添加或编辑分类时，验证数据通过');

	}


}
